<template>
	<view class="select-goods-container">

		<view class="search-area">
			<view class="search-wrapper">
				<view class="category-tab" @click="showCategoryPicker = true">
					<text class="tab-text">{{ selectedCategory.label || '全部类别' }}</text>
					<text class="tab-icon">▼</text>
				</view>
				<view class="search-box">
					<u-icon name="search" size="28" color="#c0c4cc"></u-icon>
					<input type="text" placeholder="输入货品名称/条形码直接查找" v-model="searchKeyword" @input="handleSearch" />
					<view class="clear-btn" v-if="searchKeyword" @click="clearSearch">
						<u-icon name="close-circle-fill" size="28" color="#c0c4cc"></u-icon>
					</view>
				</view>
				<view class="add-icon">
					<u-icon name="plus" size="30" color="#39C9BB" @click="goToGoodsAdd"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 商品列表区域 -->
		<scroll-view scroll-y class="goods-list" v-if="goodsList.length > 0" @scrolltolower="loadMore" :lower-threshold="10">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="selectGoods(item)">
				<view class="goods-image">
					<image :src="item.goodImage || '/static/images/default-goods.png'" mode="aspectFill"></image>
				</view>
				<view class="goods-info">
					<view class="goods-name">{{ item.name }}</view>
					<view class="goods-price">
						<text class="price-label">零售价：</text>
						<text class="price-value">¥{{ item.price || '0.00' }}</text>
					</view>
					<view class="goods-stock">库存: {{ item.stock || '18.00' }}</view>
				</view>
				<view class="add-btn" v-if="!isSelected(item)">
					<u-icon name="plus-circle" size="50" color="#39C9BB" @click.stop="addToCart(item)"></u-icon>
				</view>
				<view class="quantity-control" v-else>
					<text class="minus-btn" @click.stop="decreaseQuantity(item)">-</text>
					<text class="quantity">{{ getSelectedQuantity(item) }}</text>
					<text class="plus-btn" @click.stop="increaseQuantity(item)">+</text>
				</view>
			</view>
			
			<!-- 加载状态提示 -->
			<view class="loading-more">
				<view v-if="loading" class="loading">
					<u-loading size="24" color="#39C9BB"></u-loading>
					<text class="loading-text">正在加载更多...</text>
				</view>
				<view v-else-if="finished" class="no-more">
					<text class="no-more-text">没有更多数据了</text>
				</view>
				<view v-else class="more">
					<text class="more-text">上拉加载更多</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="goodsList.length === 0">
			<image src="/static/images/empty-data.png" class="empty-image" mode="aspectFit"></image>
			<text class="empty-text">暂无相关货品</text>
		</view>
		
		<!-- 底部结算区域 -->
		<view class="footer">
			<view class="total-info">
				<view class="total-line">
					<text class="total-label">选中货品</text>
					<text class="total-value">({{ selectedGoods.length || 0 }})</text>
				</view>
				<view class="total-line">
					<text class="total-label">合计金额：</text>
					<text class="total-value price">¥{{ totalAmount.toFixed(2) }}</text>
				</view>
			</view>
			<view class="confirm-btn" @click="confirmSelection">选好了</view>
		</view>

		<!-- 新增：分类选择器 -->
		<u-picker 
			:show="showCategoryPicker" 
			:columns="categoryColumns" 
			keyName="label" 
			@confirm="confirmCategory" 
			@cancel="showCategoryPicker = false"
		></u-picker>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	
	export default {
		data() {
			return {
				searchKeyword: '',
				goodsList: [],
				selectedGoods: [],
				totalAmount: 0,
				// 新增分类相关数据
				showCategoryPicker: false,
				categoryColumns: [],
				selectedCategory: { label: '全部类别', id: null },
				// 分页相关
				pageNum: 1,
				pageSize: 15, 
				totalPage: 1,
				loading: false,
				finished: false
			}
		},
		onLoad(options) {
			// 先加载分类数据
			this.loadCategories();
			// 再加载商品列表
			this.loadGoodsList();
		},
		methods: {
			// 加载商品列表
			loadGoodsList(isLoadMore = false) {
				if (this.loading) {
					return;
				}
				
				if (isLoadMore && this.finished) {
					console.log('已加载全部数据');
					return;
				}
				
				this.loading = true;
				
				if (!isLoadMore) {
					uni.showLoading({
						title: '加载中...'
					});
				}
				
				const params = {
					goodsSpec: this.searchKeyword.trim() || '',
					pageSize: this.pageSize,
					pageNum: this.pageNum
				};
				
				// 只有在选择了特定分类时才添加categoryId参数
				if (this.selectedCategory && this.selectedCategory.id !== null) {
					params.goodsCategoryId = this.selectedCategory.id;
				}
				
				console.log('查询商品参数:', params);
				
				api.getGoodsList(params).then(res => {
					if (!isLoadMore) {
						uni.hideLoading();
					}
					
					if (res && res.rows && Array.isArray(res.rows)) {
						// 过滤无效数据
						const validRows = res.rows.filter(item => item && typeof item === 'object');
						
						// 确保每个商品都有id和必要的属性
						const formattedGoods = validRows.map((item, index) => {
							// 如果没有id，使用其他可能的id字段或生成临时id
							const id = item.id || item.goodsId || item.productId || `temp-id-${index}`;
							
							return {
								id: id,
								name: item.goodsSpec || item.name || '未知商品',
								price: item.retailPrice || '0.00',
								stock: item.stockQuantity || '0',
								goodImage: item.goodsImage || ''
							};
						});
						
						// 更新商品列表
						if (isLoadMore) {
							this.goodsList = [...this.goodsList, ...formattedGoods];
						} else {
							this.goodsList = formattedGoods;
						}
						
						// 更新分页信息
						if (res.total !== undefined) {
							this.totalPage = Math.ceil(res.total / this.pageSize);
							this.finished = this.pageNum >= this.totalPage;
						} else {
							// 如果没有返回总数，判断当前返回条数是否小于每页数，如果是则认为已加载完
							this.finished = formattedGoods.length < this.pageSize;
						}
						
						console.log('商品列表加载成功', this.goodsList.length, '是否结束:', this.finished);
					} else {
						if (!isLoadMore) {
							this.goodsList = [];
						}
						this.finished = true;
						console.log('商品列表为空');
					}
					
					this.loading = false;
				}).catch(err => {
					console.error('获取商品列表失败:', err);
					this.loading = false;
					if (!isLoadMore) {
						uni.hideLoading();
						uni.showToast({
							title: '获取商品列表失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 搜索商品
			handleSearch() {
				// 重置分页
				this.pageNum = 1;
				this.finished = false;
				this.loadGoodsList();
			},
			
			// 清除搜索关键词
			clearSearch() {
				this.searchKeyword = '';
				this.pageNum = 1;
				this.finished = false;
				this.loadGoodsList();
			},
			
			// 选择商品
			selectGoods(item) {
				// 如果已经选中，显示数量控制器
				// 如果没有选中，添加到购物车
				if (!this.isSelected(item)) {
					this.addToCart(item);
				}
			},
			
			// 计算总金额
			calculateTotal() {
				this.totalAmount = this.selectedGoods.reduce((total, item) => {
					return total + (parseFloat(item.price) * item.quantity);
				}, 0);
			},
			
			// 确认选择
			confirmSelection() {
				if (this.selectedGoods.length === 0) {
					uni.showToast({
						title: '请至少选择一件商品',
						icon: 'none'
					});
					return;
				}
				
				// 将选中的商品数据传回上一页
				const pages = getCurrentPages();
				const prevPage = pages[pages.length - 2]; // 获取上一个页面
				
				// 调用上一个页面的方法，传递数据
				if (prevPage && prevPage.$vm && typeof prevPage.$vm.setSelectedGoods === 'function') {
					console.log('传递选中的商品:', this.selectedGoods, '总金额:', this.totalAmount);
					prevPage.$vm.setSelectedGoods(this.selectedGoods, this.totalAmount);
				} else {
					console.warn('无法找到上一页或其 $vm 或 setSelectedGoods 方法');
				}
				
				// 返回上一页
				uni.navigateBack();
			},
			
			// 检查商品是否已选中
			isSelected(item) {
				return this.selectedGoods.some(g => g.id === item.id);
			},
			
			// 获取选中商品的数量
			getSelectedQuantity(item) {
				const selected = this.selectedGoods.find(g => g.id === item.id);
				return selected ? selected.quantity : 0;
			},
			
			// 添加商品到购物车
			addToCart(item) {
				// if(item.stock == 0){
				// 	return uni.showToast({
				// 		title: '库存不足',
				// 		icon: 'none'
				// 	});
					
				// }
				// 检查是否已选中
				if (!this.isSelected(item)) {
					this.selectedGoods.push({
						...item,
						quantity: 1
					});
					
					// 计算总金额
					this.calculateTotal();
					
					uni.showToast({
						title: '已添加商品',
						icon: 'none'
					});
				}
			},
			
			// 减少商品数量
			decreaseQuantity(item) {
				const index = this.selectedGoods.findIndex(g => g.id === item.id);
				
				if (index > -1) {
					const selected = this.selectedGoods[index];
					if (selected.quantity > 1) {
						selected.quantity -= 1;
					} else {
						// 移除商品
						this.selectedGoods.splice(index, 1);
					}
					
					// 计算总金额
					this.calculateTotal();
				}
			},
			
			// 增加商品数量
			increaseQuantity(item) {
				const index = this.selectedGoods.findIndex(g => g.id === item.id);
				
				if (index > -1) {
					this.selectedGoods[index].quantity += 1;
					// 计算总金额
					this.calculateTotal();
				}
			},

			// 跳转商品添加页面
			goToGoodsAdd() {
				uni.navigateTo({ url: '/pages/goods/add' });
			},

			// 加载分类数据
			loadCategories() {
				api.getCategoryList().then(res => {
					if (res && Array.isArray(res)) {
						const categoryMap = {};
						res.forEach(item => {
							categoryMap[item.id] = {...item, children: []};
						});
						const rootCategories = [];
						res.forEach(item => {
							if (item.parentId && item.parentId !== 0 && categoryMap[item.parentId]) {
								categoryMap[item.parentId].children.push(categoryMap[item.id]);
							} else {
								rootCategories.push(categoryMap[item.id]);
							}
						});
						const flattenCategories = this.flattenCategoryTree(rootCategories);
						this.categoryColumns = [[ ...flattenCategories]];
						// 设置默认选中
						this.selectedCategory = { label: '全部类别', id: null };
					} else {
						this.categoryColumns = [[{ label: '全部类别', id: null }]];
					}
				}).catch(err => {
					console.error('加载分类数据失败:', err);
				});
			},
			flattenCategoryTree(tree) {
				let result = [];
				const process = (items, level = 0) => {
					if (!items || !Array.isArray(items) || items.length === 0) return;
					items.forEach(item => {
						if (!item || !item.categoryName) return;
						const prefix = level > 0 ? '\u3000'.repeat(level) + '└ ' : '';
						const categoryName = prefix + item.categoryName;
						result.push({
							...item,
							label: categoryName, // 使用 label 属性供 u-picker
						});
						if (item.children && Array.isArray(item.children) && item.children.length > 0) {
							process(item.children, level + 1);
						}
					});
				};
				process(tree);
				return result;
			},
			confirmCategory(e) {
				console.log('选择分类:', e);
				const selected = e.value[0];
				if (selected) {
					this.selectedCategory = { label: selected.label, id: selected.id };
					this.showCategoryPicker = false;
					console.log('已选择分类:', this.selectedCategory);
					// 根据选择的分类ID重新获取货品列表
					this.pageNum = 1; // 重置页码
					this.finished = false;
					this.loadGoodsList();
				} else {
					uni.showToast({ title: '选择分类失败', icon: 'none' });
				}
			},
			
			// 加载更多
			loadMore() {
				console.log('滚动到底部，加载更多...');
				if (!this.loading && !this.finished) {
					this.pageNum += 1;
					this.loadGoodsList(true);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.select-goods-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f7fa;
}

/* 顶部标题栏 */
.header {
	background-color: #ffffff;
	border-bottom: 1px solid #eaeaea;
	
	.title-area {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		
		.title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
		}
		
		.right-buttons {
			display: flex;
			align-items: center;
			
			.icon-minus, .icon-close {
				font-size: 40rpx;
				color: #666666;
				padding: 0 15rpx;
			}
		}
	}
}

/* 搜索区域 */
.search-area {
	background-color: #ffffff;
	padding: 20rpx;
	
	.search-wrapper {
		display: flex;
		align-items: center;
		
		.category-tab {
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			padding: 15rpx 20rpx;
			border-radius:32rpx;
			margin-right: 15rpx;
			cursor: pointer;
			
			.tab-text {
				font-size: 26rpx;
				color: #333333;
				margin-right: 8rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 150rpx;
			}
			
			.tab-icon {
				font-size: 22rpx;
				color: #666666;
			}
		}
		
		.search-box {
			flex: 1;
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 8rpx;
			padding: 0 20rpx;
			height: 72rpx;
			
			input {
				flex: 1;
				height: 100%;
				font-size: 26rpx;
				margin: 0 15rpx;
			}
			
			.clear-btn {
				padding: 10rpx;
			}
		}
		
		.add-icon {
			width: 72rpx;
			height: 72rpx;
			color: #39C9BB;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-left: 15rpx;
		}
	}
}

/* 商品列表 */
.goods-list {
	flex: 1;
	background-color: #ffffff;
	padding-bottom: 100rpx;
	height: calc(100vh - 220rpx); /* 设置固定高度，减去头部和底部的高度 */
	
	.goods-item {
		display: flex;
		padding: 30rpx 20rpx;
		border-bottom: 1px solid #f0f0f0;
		
		.goods-image {
			width: 120rpx;
			height: 120rpx;
			margin-right: 20rpx;
			
			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
				background-color: #f5f5f5;
			}
		}
		
		.goods-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			
			.goods-name {
				font-size: 28rpx;
				color: #333333;
				margin-bottom: 8rpx;
			}
			
			.goods-price {
				display: flex;
				align-items: center;
				margin-bottom: 8rpx;
				
				.price-label {
					font-size: 24rpx;
					color: #999999;
				}
				
				.price-value {
					font-size: 28rpx;
					color: #333333;
					font-weight: 500;
				}
			}
			
			.goods-stock {
				font-size: 24rpx;
				color: #999999;
			}
		}
		
		.add-btn {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
		}
		
		.quantity-control {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			
			.minus-btn, .plus-btn {
				font-size: 28rpx;
				color: #333333;
				padding: 0 10rpx;
			}
			
			.quantity {
				font-size: 28rpx;
				color: #333333;
				padding: 0 10rpx;
			}
		}
	}
}

/* 加载更多样式 */
.loading-more {
	padding: 30rpx 0;
	text-align: center;
	
	.loading, .no-more, .more {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		
		.loading-text, .no-more-text, .more-text {
			font-size: 24rpx;
			color: #999999;
			margin-left: 10rpx;
		}
	}
}

/* 空状态 */
.empty-state {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #ffffff;
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
}

/* 底部结算区域 */
.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	
	.total-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 0 30rpx;
		
		.total-line {
			display: flex;
			align-items: center;
			margin-bottom: 8rpx;
			
			.total-label {
				font-size: 24rpx;
				color: #999999;
			}
			
			.total-value {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
			}
		}
		
		.price {
			font-size: 28rpx;
			color: #fa3534;
			font-weight: 500;
		}
	}
	
	.confirm-btn {
		width: 220rpx;
		height: 100%;
		background-color: #39C9BB;
		color: #ffffff;
		font-size: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style> 